package Schema::ResultSet::Account;

use Modern::Perl;
use base 'DBIx::Class::ResultSet';

sub by_user_id {
    my ($self, $id) = @_;

    my $rs = $self->search(
        {
            'acls.user_id' => $id,
            'acls.read'    => 1,
        },
        {
            columns        => [
                'id',
                'name',
                'balance',
                { type     => 'account_type.name' },
                { currency => 'currency.name' },
            ],
            join           => [qw/
                acls
                account_type
                currency
            /],
            result_class   => 'DBIx::Class::ResultClass::HashRefInflator',
        }
    );

    my @result;

    while (my $row = $rs->next) {
        my $template = '<a href="/account/%d">%s</a>';
        $row->{name} = sprintf $template, $row->{id}, $row->{name};

        $row->{balance} = Schema::format_num($row->{balance});

        push @result, [ @$row{ qw/ name type balance currency / } ];
    }

    return @result;
}

sub id_name_by_uid {
    my ($self, $id) = @_;

    my $rs = $self->search(
        {
            'acls.user_id'  => $id,
            'acls.write'    => 1, # true
        },
        {
            columns         => [ qw/ id name / ],
            join            => 'acls',
            result_class    => 'DBIx::Class::ResultClass::HashRefInflator',
        },
    );

    my $result = {};

    while (my $row = $rs->next) {
        $result->{$row->{id}} = $row->{name};
    }

    return $result;
}

sub create {
    my ($self, $h) = @_;

    $h->{balance} =~ y/,/./;
    $h->{balance} =~ s/ //;
    $h->{balance} *= 100;

    $h->{acls} = [{
        user_id => $h->{user_id},
        read    => 1,
        write   => 1,
    }];

    return $self->next::method($h);
}

1;
